package com.njtoyo.taxi.admin.service.business.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.library.Const;
import com.njtoyo.taxi.admin.library.common.Enum;
import com.njtoyo.taxi.admin.library.common.GeoPoint;
import com.njtoyo.taxi.admin.library.common.OperationRecordHelper;
import com.njtoyo.taxi.admin.library.taxi_service.SimpleCallTaxiService;
import com.njtoyo.taxi.admin.library.taxi_service.TaxiService;
import com.njtoyo.taxi.admin.logic.business.ride.RideOrderLogic;
import com.njtoyo.taxi.admin.logic.business.ride.SimpleCallOrderLogic;
import com.njtoyo.taxi.admin.logic.business.simple_call.SimpleCallRideLogic;
import com.njtoyo.taxi.admin.logic.business.simple_call.SimpleCallRideOrderLogic;
import com.njtoyo.taxi.admin.mapper.master.entity.*;
import com.njtoyo.taxi.admin.mapper.master.enums.*;
import com.njtoyo.taxi.admin.mapper.master.enums.SimpleCallRideState;
import com.njtoyo.taxi.admin.mapper.master.mapper.*;
import com.njtoyo.taxi.admin.mapper.secondary.mapper.AdminUserMapper;
import com.njtoyo.taxi.admin.mongo.entity.primary.RideRouteMongo;
import com.njtoyo.taxi.admin.mongo.repository.primary.RideRouteRepository;
import com.njtoyo.taxi.admin.rest.export.simple_call.SimpleCallRideExportPresenter;
import com.njtoyo.taxi.admin.rest.presenter.business.ride.*;
import com.njtoyo.taxi.admin.rest.presenter.business.simple_call_ride.ListPresenter;
import com.njtoyo.taxi.admin.rest.presenter.business.simple_call_ride.SimpleCallRideListPresenter;
import com.njtoyo.taxi.admin.rest.presenter.business.simple_call_ride.SimpleCallRideVO;
import com.njtoyo.taxi.admin.rest.presenter.platfrom.AdminUserIdentityPresenter;
import com.njtoyo.taxi.admin.rest.wrapper.business.ride.OrderManageQueryDto;
import com.njtoyo.taxi.admin.rest.wrapper.business.simpleCallRide.SimpleCallRideQueryWrapper;
import com.njtoyo.taxi.admin.service.business.SimpleCallRideService;
import com.njtoyo.taxi.admin.utils.RouteDistanceCalculator;
import com.njtoyo.taxi.admin.utils.private_number.PrivateNumberClient;
import com.taxi.entity.common.RestResult;
import com.taxi.entity.common.ResultEnum;
import com.njtoyo.taxi.entity.backend.AdminUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.aggregation.ConditionalOperators;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.hutool.core.util.ObjectUtil.isNotEmpty;

@Slf4j
@Component
@DS(Const.PRIMARY_DS)
public class SimpleCallRideServiceImpl implements SimpleCallRideService {

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private SimpleCallRideCancellationMapper cancellationOrderMapper;
    @Autowired
    private SimpleCallCancelReasonLogMapper simpleCallCancelReasonLogMapper;
    @Autowired
    private RideMarkingTagMapper rideMarkingTagMapper;

    @Autowired
    private SimpleCallRideOrderMapper simpleCallRideOrderMapper;
    @Autowired
    private RideMarkingMapper rideMarkingMapper;
    @Autowired
    private SimpleCallRideCancellationMapper simpleCallRideCancellationMapper;
    @Autowired
    private SimpleCallRideStateMapper simpleCallRideStateMapper;
    @Autowired
    private GeoCantonMapper geoCantonMapper;

    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private SimpleCallCustomerMapper simpleCallCustomerMapper;
    @Autowired
    private SimpleCallMapper simpleCallMapper;
    @Autowired
    private SimpleCallRideMapper simpleCallRideMapper;
    @Autowired
    private SimpleCallRideLocateMapper simpleCallRideLocateMapper;

    @Autowired
    private DriverMapper driverMapper;

    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private TaxiOnRideMapper taxiOnRideMapper;

    @Autowired
    private SimpleCallRideLogic simpleCallRideLogic;

    @Autowired
    private SimpleCallTaxiService simpleCallTaxiService;

    @Autowired
    private SimpleCallRideOrderLogic simpleCallRideOrderLogic;

    @Autowired
    private OperationRecordHelper operationRecordHelper;

    @Autowired
    private SimpleCallCustomerFlowLogMapper simpleCallCustomerFlowLogMapper;

    @Autowired
    private TaxiMapper taxiMapper;

    @Autowired
    private TaxiService taxiService;

    @Autowired
    private GeoAreaMapper geoAreaMapper;
    @Autowired
    private SimpleRideOrderDetailMapper simpleRideOrderDetailMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private SimpleCallOrderLogic simpleCallOrderLogic;
    @Autowired
    private RideOrderLogic rideOrderLogic;
    @Autowired
    private CallRelevanceMapper callRelevanceMapper;
    @Autowired
    private RideRouteRepository rideRouteRepository;
    @Override
    public RestResult<IPage<ListPresenter>> getList(AdminUser adminUser, SimpleCallRideQueryWrapper queryWrapper) {
        // 构建 query
        LambdaQueryChainWrapper<SimpleCallRide> query = simpleCallRideLogic.getQueryForRideList(adminUser, queryWrapper);

        // 分页查询
        Page<SimpleCallRide> page = new Page<>(queryWrapper.getCurrent(), queryWrapper.getSize());

        IPage<SimpleCallRide> queryList = query.orderByDesc(SimpleCallRide::getId)
                .page(page);

        if (ObjectUtil.isEmpty(queryList.getRecords())) {
            return RestResult.success(new Page<>());
        }
        List<ListPresenter> list = new ArrayList<>();
        for (SimpleCallRide simpleCallRide : queryList.getRecords()) {
            ListPresenter listPresenter = new ListPresenter();
            BeanUtil.copyProperties(simpleCallRide, listPresenter);
            SimpleCall simpleCall = simpleCallMapper.selectById(simpleCallRide.getRefId());
            if (ObjectUtil.isNotNull(simpleCall)) {
                if (simpleCall.getState() != SimpleCallState.pick) {
                    if (simpleCall.getState() == SimpleCallState.nopick) {
                        listPresenter.setStateType("nopick");
                    } else if (simpleCall.getState() == SimpleCallState.cancelled) {
                        listPresenter.setStateType("cancelled");
                    } else if (simpleCall.getState() == SimpleCallState.covered) {
                        listPresenter.setStateType("covered");
                    }
                    listPresenter.setStateType(simpleCall.getState().name());
                } else {
                    if (simpleCallRide.getIsCancel()) {
                        SimpleCallRideCancellation ride_cancellation = new LambdaQueryChainWrapper<>(simpleCallRideCancellationMapper)
                                .select(SimpleCallRideCancellation::getTriggerBy)
                                .eq(SimpleCallRideCancellation::getRideId, simpleCallRide.getId())
                                .one();
                        if (ride_cancellation.getTriggerBy() == SimpleCallRideCancellationTriggerBy.driver) {
                            listPresenter.setStateType("cancel_driver");
                        } else if (ride_cancellation.getTriggerBy() == SimpleCallRideCancellationTriggerBy.customer) {
                            listPresenter.setStateType("cancel_customer");
                        } else if (ride_cancellation.getTriggerBy() == SimpleCallRideCancellationTriggerBy.admin) {
                            listPresenter.setStateType("cancel_admin");
                        }
                    } else {
                        if (simpleCallRide.getIsFinished()) {
                            listPresenter.setStateType("finished");
                        } else {
                            if (simpleCallRide.getState() == SimpleCallRideState.pickUp) {
                                listPresenter.setStateType("pickUp");
                            } else if (simpleCallRide.getState() == SimpleCallRideState.inArea) {
                                listPresenter.setStateType("inArea");
                            } else if (simpleCallRide.getState() == SimpleCallRideState.start) {
                                listPresenter.setStateType("start");
                            } else if (simpleCallRide.getState() == SimpleCallRideState.end) {
                                listPresenter.setStateType("end");
                            }
                        }
                    }
                }
            }
            list.add(listPresenter);
        }


        IPage<ListPresenter> response = new Page<>();
        response.setRecords(list);
        response.setCurrent(queryList.getCurrent());
        response.setSize(queryList.getSize());
        response.setPages(queryList.getPages());
        response.setTotal(queryList.getTotal());

        return RestResult.success(response);
    }


    @Override
    public RestResult<IPage<SimpleCallRideVO>> getSimpleCallPhoneRideList(AdminUser adminUser, SimpleCallRideQueryWrapper queryWrapper) {

        // 分页查询
        Page<SimpleCallRideVO> page = new Page<>(queryWrapper.getCurrent(), queryWrapper.getSize());
        if (ObjectUtil.isNotNull(queryWrapper.getStartDate()) && ObjectUtil.isNotNull(queryWrapper.getEndDate())) {
            queryWrapper.setStartDate(DateUtil.beginOfDay(queryWrapper.getStartDate()));
            queryWrapper.setEndDate(DateUtil.endOfDay(queryWrapper.getEndDate()));
        }

        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        switch (adminUser.getAccountType()) {
            case canton:
                queryWrapper.setCantonIds(identity.getCantonIds());
                break;
            case company:
                queryWrapper.setCompanyIds(identity.getCompanyIds());
                break;
        }

        IPage<SimpleCallRideVO> queryList = simpleCallRideMapper.getPageList(page, queryWrapper);

        if (ObjectUtil.isEmpty(queryList.getRecords())) {
            return RestResult.success(new Page<>());
        }
        List<Integer> adminIds = new ArrayList<>();
        queryList.getRecords().forEach(ride -> {
            adminIds.add(ride.getAdminId());
        });
        Map<Integer, String> rideAdminMap = new HashMap<>();
        if (ObjectUtil.isNotEmpty(adminIds)) {
            List<com.njtoyo.taxi.admin.mapper.secondary.entity.AdminUser> adminUsers = adminUserMapper.selectBatchIds(adminIds);
            if (CollUtil.isNotEmpty(adminUsers)) {
                rideAdminMap = adminUsers.stream().collect(Collectors.toMap(com.njtoyo.taxi.admin.mapper.secondary.entity.AdminUser::getId, com.njtoyo.taxi.admin.mapper.secondary.entity.AdminUser::getName));
            }
        }


        for (SimpleCallRideVO vo : queryList.getRecords()) {
            vo.setAdminName(rideAdminMap.get(vo.getAdminId()));
            if (vo.getIsCancel()) {
                SimpleCallRideCancellation ride_cancellation = new LambdaQueryChainWrapper<>(simpleCallRideCancellationMapper)
                        .select(SimpleCallRideCancellation::getTriggerBy)
                        .eq(SimpleCallRideCancellation::getRideId, vo.getId())
                        .orderByDesc(SimpleCallRideCancellation::getCreatedAt)
                        .last("limit 1").one();
                if (ObjectUtil.isNull(ride_cancellation)) {
                    vo.setStateType("cancel_system");
                    continue;
                }
                if (ride_cancellation.getTriggerBy() == SimpleCallRideCancellationTriggerBy.driver) {
                    vo.setStateType("cancel_driver");
                } else if (ride_cancellation.getTriggerBy() == SimpleCallRideCancellationTriggerBy.customer) {
                    vo.setStateType("cancel_customer");
                } else if (ride_cancellation.getTriggerBy() == SimpleCallRideCancellationTriggerBy.admin) {
                    vo.setStateType("cancel_admin");
                }
            } else {
                if (vo.getIsFinished()) {
                    vo.setStateType("finished");
                } else {
                    if (vo.getState() == SimpleCallRideState.pickUp) {
                        vo.setStateType("pickUp");
                    } else if (vo.getState() == SimpleCallRideState.inArea) {
                        vo.setStateType("inArea");
                    } else if (vo.getState() == SimpleCallRideState.start) {
                        vo.setStateType("start");
                    } else if (vo.getState() == SimpleCallRideState.end) {
                        vo.setStateType("end");
                    }
                }
            }
        }
        return RestResult.success(queryList);
    }

    @Override
    public RestResult<IPage<RideListPresenter>> getPageList(AdminUser adminUser, SimpleCallRideQueryWrapper wrapper) {
        IPage<RideListPresenterDTO> page = simpleCallRideMapper.getList(new Page<>(wrapper.getCurrent(), wrapper.getSize()), wrapper);


        List<RideListPresenter> listPresenters = new ArrayList<>();
        for (RideListPresenterDTO dto : page.getRecords()) {
            RideListPresenter rideListPresenter = new RideListPresenter();
            rideListPresenter.setUser(new RideListPresenter.User().setId(dto.getUserId()).setMobileNumber(dto.getUserMobileNumber()).setName(dto.getUserName()));
            rideListPresenter.setDriver(new RideListPresenter.Driver().setId(dto.getDriverId()).setMobileNumber(dto.getDriverMobileNumber()).setName(dto.getDriverName()));
            rideListPresenter.setTaxi(new RideListPresenter.Taxi().setPlateNumber(dto.getPlateNumber()));
            rideListPresenter.setId(dto.getId());
            rideListPresenter.setState(dto.getRideState());
            rideListPresenter.setPlatform(dto.getPlatform());
            rideListPresenter.setCategory(dto.getCategory());
            rideListPresenter.setCreatedAt(dto.getCreatedAt());
            rideListPresenter.setOriginName(dto.getOriginName());
            rideListPresenter.setCallOriginName(dto.getCallOriginName());
            rideListPresenter.setDestinationName(dto.getDestinationName());
            rideListPresenter.setCallDestinationName(dto.getCallDestinationName());
            rideListPresenter.setArea(new RideListPresenter.Area().setName(dto.getAreaName()));
            RideListPresenter.RideOrder rideOrder = new RideListPresenter.RideOrder();
            if (ObjectUtil.isNotNull(dto.getPayType())) {
                if (dto.getPayType() == 0) {
                    rideListPresenter.setRideOrder(rideOrder.setPaidThrough(RideOrderPaidThrough.cash));
                } else {
                    rideListPresenter.setRideOrder(rideOrder.setPaidThrough(RideOrderPaidThrough.online));
                }
            }
            if (ObjectUtil.isNotNull(dto.getPayResult())) {
                if (dto.getPayResult() == 0) {
                    rideListPresenter.setRideOrder(rideOrder.setState(RideOrderState.init));
                } else {
                    rideListPresenter.setRideOrder(rideOrder.setState(RideOrderState.done));
                }
            }
            rideListPresenter.setRideOrder(rideOrder.setId(dto.getRideOrderId()).setAmount(dto.getRideOrderAmount()));
            listPresenters.add(rideListPresenter);
        }

        IPage<RideListPresenter> suspiciousPage = new Page<>();
        suspiciousPage.setCurrent(page.getCurrent());
        suspiciousPage.setPages(page.getPages());
        suspiciousPage.setSize(page.getSize());
        suspiciousPage.setTotal(page.getTotal());
        suspiciousPage.setRecords(listPresenters);
        return RestResult.success(suspiciousPage);


    }

    @Override
    public RestResult getCountMsg(AdminUser adminUser, SimpleCallRideQueryWrapper wrapper) {
        Integer count = 0;
        List<SimpleCall> calls = simpleCallMapper.selectList(Wrappers.<SimpleCall>lambdaQuery()
                .eq(SimpleCall::getCategory, SimpleCallRideCategory.phone_appointment)
                .eq(SimpleCall::getState, SimpleCallState.pick)
                .between(SimpleCall::getScheduleTime, DateUtil.date(), DateUtil.offsetMinute(DateUtil.date(), 30)));
        if (ObjectUtil.isNotEmpty(calls)) {
            List<Long> callIds = calls.stream().map(SimpleCall::getId).collect(Collectors.toList());
            count = simpleCallRideMapper.selectCount(Wrappers.<SimpleCallRide>lambdaQuery()
                    .in(SimpleCallRide::getRefId, callIds)
                    .eq(SimpleCallRide::getState, SimpleCallRideState.pickUp));
        }
        return RestResult.success(count);
    }

    @Override
    public RestResult cancelBy(Long id, String triggerBy) {
        SimpleCallRide ride = simpleCallRideMapper.selectById(id);
        if (Objects.isNull(ride)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        // 判断行程状态
        if (ride.getIsFinished()) {
            return RestResult.failed("行程已结束");
        }
        if (ride.getIsCancel()) {
            return RestResult.failed("行程已取消");
        }
        if (!Arrays.asList(SimpleCallRideState.pickUp, SimpleCallRideState.inArea).contains(ride.getState())) {
            return RestResult.failed("行程已开始");
        }

        taxiOnRideMapper.delete(Wrappers.<TaxiOnRide>lambdaQuery()
                .eq(TaxiOnRide::getSimpleCallRideId, ride.getId()));


        SimpleCallRideCancellationTriggerBy triggerByEnum = "driver".equals(triggerBy) ? SimpleCallRideCancellationTriggerBy.driver : SimpleCallRideCancellationTriggerBy.customer;
        if ("driver".equals(triggerBy)) {
            SimpleCallCustomer simpleCallCustomer = simpleCallCustomerMapper.selectById(ride.getCustomerId());
            simpleCallTaxiService.sendMsg(simpleCallCustomer.getMobileNumber(), "SMS_465925269", "");
        }

        // 操作数据
        simpleCallRideLogic.cancelBy(ride, triggerByEnum);
        simpleCallTaxiService.sendRideStateMqtt(ride);
        //解绑隐私通话
        List<CallRelevance> callRelevances = callRelevanceMapper.selectList(Wrappers.<CallRelevance>lambdaQuery().eq(CallRelevance::getRideId, ride.getId()));
        for (CallRelevance callRelevance : callRelevances) {
            boolean unbindResult = PrivateNumberClient.unbindMobileNumber(callRelevance.getSubscriptionId());
            if (unbindResult) {
                callRelevance.setIsEffective(false);
                callRelevanceMapper.updateById(callRelevance);
            }
        }
        return RestResult.success();
    }

    @Override
    @DSTransactional
    public RestResult refundOrder(Long rideId) {
        log.info("开始执行退款操作,行程ID:{}", rideId);
        SimpleCallRide ride = simpleCallRideMapper.selectById(rideId);
        if (ObjectUtil.isEmpty(ride)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        // 判断该行程是否存在已付款的订单
        SimpleCallRideOrder rideOrder = simpleCallOrderLogic.getPaidOrderByRideId(rideId);
        if (!Objects.nonNull(rideOrder)) {
            return RestResult.failed("此行程没有已付款订单");
        }

        // 订单已退款
        if (ObjectUtil.isNotNull(rideOrder.getIsRefund()) && rideOrder.getIsRefund()) {
            return RestResult.failed("此行程订单在本操作前已被退款");
        }

        log.info(String.format("开始行程退款，行程ID [%d]", rideId));
        if (rideOrder.getPaymentChannel() != SimpleCallRideOrderPaymentChannel.wx_pay) {
            return RestResult.failed("此订单的付款渠道暂不支持退款");
        }


        boolean thirdPayRefundSuccess = simpleCallOrderLogic.cmbRefund(rideOrder, Enum.RideRefundWxAppType.wxmina);


        // //第三方支付退款成功，继续做余额退款和状态修改
        if (thirdPayRefundSuccess) {
            // 删除对应司机收入流水
            log.info("删除对应司机收入流水[开始]");
            rideOrderLogic.deleteDriverFlowLogByOrderId(rideOrder.getId(), DriverFlowLogCategory.simple_call_order);
            log.info("删除对应司机收入流水[结束]");

            operationRecordHelper.addBusinessLog(String.format("行程订单退款,行程id: [%d]", ride.getId()));

        } else {
            return RestResult.failed("退款失败 ");
        }

        return RestResult.success("操作成功");
    }

    @Override
    public List<OrderManageVo> getOneClickOrderManageVoList(AdminUser adminUser, OrderManageQueryDto dto) {
        List<OrderManageVo> list = new ArrayList<>();
        ArrayList<SimpleCallRideCategory> categories = new ArrayList<>();
        categories.add(SimpleCallRideCategory.simple);
        categories.add(SimpleCallRideCategory.my_nanjing_simple);
        dto.setOneClickCategoryList(categories);
        if (ObjectUtil.isNotNull(dto.getStartDate()) && ObjectUtil.isNotNull(dto.getEndDate())) {
            dto.setStartDate(DateUtil.beginOfDay(dto.getStartDate()));
            dto.setEndDate(DateUtil.endOfDay(dto.getEndDate()));
        }
        log.info("查询一键叫车");
        List<SimpleCallRideVO> simpleCallPhoneRideAll = simpleCallRideMapper.getOneClickSimpleCallPhoneRideAll(dto);
        if (CollectionUtils.isNotEmpty(simpleCallPhoneRideAll)) {
            for (SimpleCallRideVO simpleCallRideVO : simpleCallPhoneRideAll) {
                OrderManageVo orderManageVo = new OrderManageVo();
                orderManageVo.setId(simpleCallRideVO.getId());
                //订单号
                orderManageVo.setOrderId(simpleCallRideVO.getId().toString());
                //司机
                orderManageVo.setDriverName(simpleCallRideVO.getDriverName());
                orderManageVo.setDriverId(simpleCallRideVO.getDriverId().toString());
                orderManageVo.setDriverPhoneNumber(simpleCallRideVO.getDriverMobileNumber());
                orderManageVo.setVehicleNumber(simpleCallRideVO.getTaxiPlateNumber());
                //乘客
                orderManageVo.setPassengerName(simpleCallRideVO.getCustomerName());
                orderManageVo.setPassengerId(simpleCallRideVO.getCustomerId().toString());
                orderManageVo.setPassengerPhoneNumber(simpleCallRideVO.getCustomerMobileNumber());
                orderManageVo.setOrderTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(simpleCallRideVO.getCreatedAt()));
                //起始点
                if(StringUtils.isNotBlank(simpleCallRideVO.getOriginName())){
                    orderManageVo.setCallOriginName(simpleCallRideVO.getOriginName());
                }
                if(StringUtils.isNotBlank(simpleCallRideVO.getDestinationName())){
                    orderManageVo.setCallDestinationName(simpleCallRideVO.getDestinationName());
                }
                if(StringUtils.isNotBlank(simpleCallRideVO.getRealOriginName())){
                    orderManageVo.setOriginName(simpleCallRideVO.getRealOriginName());
                }
                if(StringUtils.isNotBlank(simpleCallRideVO.getRealDestinationName())){
                    orderManageVo.setDestinationName(simpleCallRideVO.getRealDestinationName());
                }
                orderManageVo.setIsCancel(simpleCallRideVO.getIsCancel());
                orderManageVo.setIsFinished(simpleCallRideVO.getIsFinished());
                //订单状态
                if(simpleCallRideVO.getIsCancel())
                {
                    //已取消
                    orderManageVo.setOrderState(simpleCallRideVO.getTriggerBy().getDesc() + "取消");
                }else{
                    //支付信息
                    if(1 == simpleCallRideVO.getIsPaid())
                    {
                        if(null != simpleCallRideVO.getAmount()){
                            orderManageVo.setAmount(simpleCallRideVO.getAmount());
                            orderManageVo.setPaidState("已支付");
                        }
                        if(ObjectUtils.isNotEmpty(simpleCallRideVO.getPaymentChannel())){
                            orderManageVo.setPaidThrough(simpleCallRideVO.getPaymentChannel().getDesc());
                        }
                    }
                    if(ObjectUtils.isNotEmpty(simpleCallRideVO.getState())){
                        orderManageVo.setOrderState(simpleCallRideVO.getState().getDesc());
                        if(0 == simpleCallRideVO.getState().getCode()){
                            orderManageVo.setOrderStateEn("pickUp");
                        }else if(1 == simpleCallRideVO.getState().getCode())
                        {
                            orderManageVo.setOrderStateEn("inArea");
                        }else if(2 == simpleCallRideVO.getState().getCode())
                        {
                            orderManageVo.setOrderStateEn("start");
                        }else if(3 == simpleCallRideVO.getState().getCode())
                        {
                            orderManageVo.setOrderStateEn("end");
                        }
                    }
                }
                orderManageVo.setTabName("一键叫车");

                list.add(orderManageVo);
            }
            return list;
        }
        return null;
    }

    @Override
    public List<OrderManageVo> getOldSimpleOrderManageVoList(AdminUser adminUser, OrderManageQueryDto dto) {
        List<OrderManageVo> list = new ArrayList<>();
        ArrayList<SimpleCallRideCategory> oldCategories = new ArrayList<>();
        oldCategories.add(SimpleCallRideCategory.old_simple);
        dto.setOldCategoryList(oldCategories);
        if (ObjectUtil.isNotNull(dto.getStartDate()) && ObjectUtil.isNotNull(dto.getEndDate())) {
            dto.setStartDate(DateUtil.beginOfDay(dto.getStartDate()));
            dto.setEndDate(DateUtil.endOfDay(dto.getEndDate()));
        }
        log.info("查询助老屏");
        List<SimpleCallRideVO> simpleCallPhoneRideAll = simpleCallRideMapper.getOldSimpleCallPhoneRideAll(dto);
        if (CollectionUtils.isNotEmpty(simpleCallPhoneRideAll)) {
            for (SimpleCallRideVO simpleCallRideVO : simpleCallPhoneRideAll) {
                OrderManageVo orderManageVo = new OrderManageVo();
                orderManageVo.setId(simpleCallRideVO.getId());
                //订单号
                orderManageVo.setOrderId(simpleCallRideVO.getId().toString());
                //司机
                orderManageVo.setDriverName(simpleCallRideVO.getDriverName());
                orderManageVo.setDriverId(simpleCallRideVO.getDriverId().toString());
                orderManageVo.setDriverPhoneNumber(simpleCallRideVO.getDriverMobileNumber());
                orderManageVo.setVehicleNumber(simpleCallRideVO.getTaxiPlateNumber());
                //乘客
                orderManageVo.setPassengerName(simpleCallRideVO.getCustomerName());
                orderManageVo.setPassengerId(simpleCallRideVO.getCustomerId().toString());
                orderManageVo.setPassengerPhoneNumber(simpleCallRideVO.getCustomerMobileNumber());
                orderManageVo.setOrderTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(simpleCallRideVO.getCreatedAt()));
                //起始点
                if(StringUtils.isNotBlank(simpleCallRideVO.getOriginName())){
                    orderManageVo.setCallOriginName(simpleCallRideVO.getOriginName());
                }
                if(StringUtils.isNotBlank(simpleCallRideVO.getDestinationName())){
                    orderManageVo.setCallDestinationName(simpleCallRideVO.getDestinationName());
                }
                if(StringUtils.isNotBlank(simpleCallRideVO.getRealOriginName())){
                    orderManageVo.setOriginName(simpleCallRideVO.getRealOriginName());
                }
                if(StringUtils.isNotBlank(simpleCallRideVO.getRealDestinationName())){
                    orderManageVo.setDestinationName(simpleCallRideVO.getRealDestinationName());
                }
                orderManageVo.setIsCancel(simpleCallRideVO.getIsCancel());
                orderManageVo.setIsFinished(simpleCallRideVO.getIsFinished());

                //订单状态
                if(simpleCallRideVO.getIsCancel())
                {
                    //已取消
                    orderManageVo.setOrderState(simpleCallRideVO.getTriggerBy().getDesc() + "取消");
                }else{
                    //支付信息
                    if(1 == simpleCallRideVO.getIsPaid())
                    {
                        if(null != simpleCallRideVO.getAmount()){
                            orderManageVo.setAmount(simpleCallRideVO.getAmount());
                            orderManageVo.setPaidState("已支付");
                        }
                        if(ObjectUtils.isNotEmpty(simpleCallRideVO.getPaymentChannel())){
                            orderManageVo.setPaidThrough(simpleCallRideVO.getPaymentChannel().getDesc());
                        }
                    }
                    if(ObjectUtils.isNotEmpty(simpleCallRideVO.getState())){
                        orderManageVo.setOrderState(simpleCallRideVO.getState().getDesc());
                        if(0 == simpleCallRideVO.getState().getCode()){
                            orderManageVo.setOrderStateEn("pickUp");
                        }else if(1 == simpleCallRideVO.getState().getCode())
                        {
                            orderManageVo.setOrderStateEn("inArea");
                        }else if(2 == simpleCallRideVO.getState().getCode())
                        {
                            orderManageVo.setOrderStateEn("start");
                        }else if(3 == simpleCallRideVO.getState().getCode())
                        {
                            orderManageVo.setOrderStateEn("end");
                        }
                    }
                }
                orderManageVo.setTabName("助老屏");
                list.add(orderManageVo);
            }
            return list;
        }
        return null;
    }


    @Override
    public RestResult rideListExport(AdminUser adminUser, SimpleCallRideQueryWrapper wrapper, HttpServletResponse
            response) throws IOException {
        wrapper.setCategory(SimpleCallRideCategory.phone);

        // 构建 query
        LambdaQueryChainWrapper<SimpleCallRide> query = simpleCallRideLogic.getQueryForRideList(adminUser, wrapper);

        // 校验数据量
        Integer limitCount = 5000;
        if (query.count() > limitCount) {
            return RestResult.failed("数据量过大,请缩小筛选范围再导出");
        }

        // 不分页查询
        List<SimpleCallRide> queryList = query.orderByDesc(SimpleCallRide::getId)
                .list();

        List<ListPresenter> res = new ArrayList<>();

        if (ObjectUtil.isNotEmpty(queryList)) {
            res = simpleCallRideLogic.convertRideQueryList(queryList);
        }

        String fileName = URLEncoder.encode("电召行程导出", "UTF-8").replaceAll("\\+", "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SimpleCallRideExportPresenter.class)
                .sheet(0)
                .doWrite(res);

        return null;
    }

    @Override
    public RestResult<SimpleRideDetailPresenter> detail(Long id) {
        SimpleCallRide ride = simpleCallRideMapper.selectById(id);
        if (ObjectUtil.isEmpty(ride)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }


        SimpleRideDetailPresenter res = BeanUtil.copyProperties(ride, SimpleRideDetailPresenter.class);
        res.setCallOriginName(ride.getOriginName());

        SimpleCall simpleCall = simpleCallMapper.selectById(ride.getRefId());
        res.setCallId(ride.getRefId());
        if (simpleCall.getCategory() == SimpleCallRideCategory.phone_appointment) {
            res.setUseTaxiDate(simpleCall.getScheduleTime());
        } else if (ObjectUtil.isNotNull(simpleCall) && ObjectUtil.isNotNull(simpleCall.getCreatedAt())) {
            res.setUseTaxiDate(simpleCall.getCreatedAt());
        }


        // taxi
        if (Objects.nonNull(ride.getTaxiId())) {
            Taxi taxi = new LambdaQueryChainWrapper<>(taxiMapper)
                    .select(Taxi::getId, Taxi::getPlateNumber)
                    .eq(Taxi::getId, ride.getTaxiId())
                    .one();
            if (Objects.nonNull(taxi)) {
                res.setTaxi(BeanUtil.copyProperties(taxi, SimpleRideDetailPresenter.Taxi.class));
            }
        }
        // driver
        if (Objects.nonNull(ride.getDriverId())) {
            Driver driver = new LambdaQueryChainWrapper<>(driverMapper)
                    .select(Driver::getId, Driver::getName, Driver::getMobileNumber)
                    .eq(Driver::getId, ride.getDriverId())
                    .one();
            if (Objects.nonNull(driver)) {
                res.setDriver(BeanUtil.copyProperties(driver, SimpleRideDetailPresenter.Driver.class));
            }
        }

        // company
        if (Objects.nonNull(ride.getCompanyId())) {
            Company company = new LambdaQueryChainWrapper<>(companyMapper)
                    .select(Company::getId, Company::getName)
                    .eq(Company::getId, ride.getCompanyId())
                    .one();
            if (Objects.nonNull(company)) {
                res.setCompany(BeanUtil.copyProperties(company, SimpleRideDetailPresenter.Company.class));
            }
        }

        // user
        if (Objects.nonNull(ride.getCustomerId())) {
            SimpleCallCustomer customer = new LambdaQueryChainWrapper<>(simpleCallCustomerMapper)
                    .select(SimpleCallCustomer::getId, SimpleCallCustomer::getName, SimpleCallCustomer::getMobileNumber)
                    .eq(SimpleCallCustomer::getId, ride.getCustomerId())
                    .one();
            if (Objects.nonNull(customer)) {
                res.setUser(BeanUtil.copyProperties(customer, SimpleRideDetailPresenter.User.class));
            }
        }

        // area
        if (Objects.nonNull(ride.getAreaId())) {
            GeoArea area = new LambdaQueryChainWrapper<>(geoAreaMapper)
                    .select(GeoArea::getId, GeoArea::getName, GeoArea::getCityId)
                    .eq(GeoArea::getId, ride.getAreaId())
                    .one();
            if (Objects.nonNull(area)) {
                res.setArea(BeanUtil.copyProperties(area, SimpleRideDetailPresenter.Area.class));

                // city
                if (Objects.nonNull(area.getCityId())) {
                    City city = new LambdaQueryChainWrapper<>(cityMapper)
                            .select(City::getId, City::getName)
                            .eq(City::getId, area.getCityId())
                            .one();
                    if (Objects.nonNull(city)) {
                        res.setCity(BeanUtil.copyProperties(city, SimpleRideDetailPresenter.City.class));
                    }
                }
            }
        }

        // canton
        if (Objects.nonNull(ride.getCantonId())) {
            GeoCanton canton = new LambdaQueryChainWrapper<>(geoCantonMapper)
                    .select(GeoCanton::getId, GeoCanton::getName)
                    .eq(GeoCanton::getId, ride.getCantonId())
                    .one();
            if (Objects.nonNull(canton)) {
                res.setCanton(BeanUtil.copyProperties(canton, SimpleRideDetailPresenter.Canton.class));
            }
        }

        // ride_order
        SimpleCallRideOrder ride_order = new LambdaQueryChainWrapper<>(simpleCallRideOrderMapper)
                .in(SimpleCallRideOrder::getRideId, id)
                .one();

        if (Objects.nonNull(ride_order)) {
            SimpleRideDetailPresenter.RideOrder rideOrder = BeanUtil.copyProperties(ride_order, SimpleRideDetailPresenter.RideOrder.class);
            if (ObjectUtil.isNotNull(ride_order.getIsPaid()) && ride_order.getIsPaid()) {
                if (!ride_order.getIsOnline()) {
                    rideOrder.setPaidThrough(RideOrderPaidThrough.cash);
                } else {
                    rideOrder.setPaidThrough(RideOrderPaidThrough.online);
                }
            }

            SimpleRideOrderDetail simpleRideOrderDetail = simpleRideOrderDetailMapper.selectOne(Wrappers.<SimpleRideOrderDetail>lambdaQuery().eq(SimpleRideOrderDetail::getRideId, id));
            if (ObjectUtil.isNotNull(simpleRideOrderDetail)) {
                rideOrder.setTaxiFee(ObjectUtil.isNotEmpty(simpleRideOrderDetail.getTaxiFee()) ? simpleRideOrderDetail.getTaxiFee() : new BigDecimal(0));
                rideOrder.setTollFee(ObjectUtil.isNotEmpty(simpleRideOrderDetail.getTollFee()) ? simpleRideOrderDetail.getTollFee() : new BigDecimal(0));
                rideOrder.setOtherFee(ObjectUtil.isNotEmpty(simpleRideOrderDetail.getOtherFee()) ? simpleRideOrderDetail.getOtherFee() : new BigDecimal(0));
            } else {
                rideOrder.setTaxiFee(new BigDecimal(0));
                rideOrder.setTollFee(new BigDecimal(0));
                rideOrder.setOtherFee(new BigDecimal(0));
            }
            res.setIsOnline(ride_order.getIsOnline());
            rideOrder.setFarePaid(ride_order.getCustomerFarePaid());
            res.setIsPaid(ride_order.getIsPaid());
            res.setRideOrder(rideOrder);
        }

        // ride_state
        List<com.njtoyo.taxi.admin.mapper.master.entity.SimpleCallRideState> rideStateList = new LambdaQueryChainWrapper<>(simpleCallRideStateMapper)
                .eq(com.njtoyo.taxi.admin.mapper.master.entity.SimpleCallRideState::getRideId, ride.getId())
                .list();
        if (ObjectUtil.isNotEmpty(rideStateList)) {
            List<SimpleRideDetailPresenter.RideStateLog> rideStateLogList = new ArrayList<>();
            rideStateList.forEach(i -> {
                SimpleRideDetailPresenter.RideStateLog rideStateLog = BeanUtil.copyProperties(i, SimpleRideDetailPresenter.RideStateLog.class);
                rideStateLogList.add(rideStateLog);
            });
            res.setRideStateLog(rideStateLogList);
        }

        // ride_cancellation
        SimpleCallRideCancellation ride_cancellation = new LambdaQueryChainWrapper<>(simpleCallRideCancellationMapper)
                .select(SimpleCallRideCancellation::getId, SimpleCallRideCancellation::getRideId, SimpleCallRideCancellation::getTriggerBy, SimpleCallRideCancellation::getCreatedAt, SimpleCallRideCancellation::getUpdatedAt)
                .eq(SimpleCallRideCancellation::getRideId, ride.getId())
                .one();

        if (Objects.nonNull(ride_cancellation)) {
            SimpleRideDetailPresenter.RideCancellation rideCancellation = BeanUtil.copyProperties(ride_cancellation, SimpleRideDetailPresenter.RideCancellation.class);
            res.setRideCancellation(rideCancellation);
        }

        // ride_marking
        RideMarking ride_marking = new LambdaQueryChainWrapper<>(rideMarkingMapper)
                .select(RideMarking::getId, RideMarking::getScore, RideMarking::getComment, RideMarking::getCreatedAt)
                .eq(RideMarking::getRideId, ride.getId())
                .one();
        if (Objects.nonNull(ride_marking)) {
            // 设置score，category
            SimpleRideDetailPresenter.RideMarking rideMarking = BeanUtil.copyProperties(ride_marking, SimpleRideDetailPresenter.RideMarking.class);

            // ride_marking_tag
            List<RideMarkingTag> rideMarkingTagList = new LambdaQueryChainWrapper<>(rideMarkingTagMapper)
                    .eq(RideMarkingTag::getId, ride_marking.getId())
                    .list();

            // 获取tag
            if (ObjectUtil.isNotEmpty(rideMarkingTagList)) {
                List<Long> tagIds = rideMarkingTagList.stream().map(RideMarkingTag::getTagId).collect(Collectors.toList());
                // 根据tagIds查询tag
                List<Tag> tagList = new LambdaQueryChainWrapper<>(tagMapper)
                        .in(Tag::getId, tagIds)
                        .list();
                if (ObjectUtil.isNotEmpty(tagList)) {
                    List<SimpleRideDetailPresenter.RideMarkingTag> rideMarkingTags = new ArrayList<>();

                    for (Tag tag : tagList) {
                        SimpleRideDetailPresenter.RideMarkingTag rideMarkingTagSub = new SimpleRideDetailPresenter.RideMarkingTag();
                        rideMarkingTagSub.setId(tag.getId());
                        rideMarkingTagSub.setTitle(tag.getTitle());
                        rideMarkingTagSub.setCategory(tag.getCategory());
                        rideMarkingTags.add(rideMarkingTagSub);
                    }

                    rideMarking.setRideMarkingTag(rideMarkingTags);
                }
            }
            res.setRideMarking(rideMarking);
        }

        return RestResult.success(res);
    }

    @Override
    public RestResult cancel(AdminUser adminUser, Long id) {
        SimpleCallRide ride = simpleCallRideMapper.selectById(id);
        if (Objects.isNull(ride)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        // 判断行程状态
        if (ride.getIsFinished()) {
            return RestResult.failed("行程已结束");
        }
        if (ride.getIsCancel()) {
            return RestResult.failed("行程已取消");
        }
        if (!Arrays.asList(SimpleCallRideState.pickUp, SimpleCallRideState.inArea).contains(ride.getState())) {
            return RestResult.failed("行程已开始");
        }

        taxiOnRideMapper.delete(Wrappers.<TaxiOnRide>lambdaQuery()
                .eq(TaxiOnRide::getSimpleCallRideId, ride.getId()));

        // 操作数据
        simpleCallRideLogic.cancel(ride);
        simpleCallTaxiService.sendRideStateMqtt(ride);
        //解绑隐私通话
        List<CallRelevance> callRelevances = callRelevanceMapper.selectList(Wrappers.<CallRelevance>lambdaQuery().eq(CallRelevance::getRideId, ride.getId()));
        for (CallRelevance callRelevance : callRelevances) {
            boolean unbindResult = PrivateNumberClient.unbindMobileNumber(callRelevance.getSubscriptionId());
            if (unbindResult) {
                callRelevance.setIsEffective(false);
                callRelevanceMapper.updateById(callRelevance);
            }
        }
        return RestResult.success();
    }

    @Override
    public RestResult start(AdminUser adminUser, Long id) {
        SimpleCallRide ride = simpleCallRideMapper.selectById(id);
        if (Objects.isNull(ride)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        // 判断行程状态
        if (ride.getIsFinished()) {
            return RestResult.failed("行程已结束");
        }
        if (ride.getIsCancel()) {
            return RestResult.failed("行程已取消");
        }
        if (!Arrays.asList(SimpleCallRideState.pickUp, SimpleCallRideState.inArea).contains(ride.getState())) {
            return RestResult.failed("行程已开始");
        }

        // 操作数据
        simpleCallRideLogic.start(ride);
        simpleCallTaxiService.sendRideStateMqtt(ride);
        return RestResult.success();
    }

    @Override
    @DSTransactional
    public RestResult<Boolean> onlineOrderSetOffline(Long id) {
        SimpleCallRide ride = simpleCallRideMapper.selectById(id);
        if (ObjectUtil.isEmpty(ride)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        if (SimpleCallRideCategory.phone.equals(ride.getCategory())) {
            return RestResult.failed("操作失败，非一键叫车行程订单");
        }

        // 判断ride是否处于完成待付款状态
        if (!SimpleCallRideState.end.equals(ride.getState())) {
            return RestResult.failed("此行程不处于完成待付款状态");
        }

        // 判断ride的is_finished是否为0
        if (ride.getIsFinished()) {
            return RestResult.failed("操作失败，此行程已经结束");
        }

        // 判断ride是否为取消
        if (ride.getIsCancel()) {
            return RestResult.failed("操作失败，此行程已经取消");
        }

        SimpleCallRideOrder rideOrder = simpleCallRideLogic.getUnpaidOrderByRideId(id);
        if (Objects.isNull(rideOrder)) {
            return RestResult.failed("此行程没有未付款行程订单，或已经完成支付");
        }

        // 判断行程订单付款方式是否为线下付款
        if (!rideOrder.getIsOnline()) {
            return RestResult.failed("此行程已经是线下支付方式");
        }

        taxiOnRideMapper.delete(Wrappers.<TaxiOnRide>lambdaQuery()
                .eq(TaxiOnRide::getSimpleCallRideId, ride.getId()));

        // 操作 SimpleCallRide 表
        boolean updateRide = simpleCallRideLogic.onlineOrderSetOffline(id);

        // 操作 SimpleCallRideOrder 表
        boolean updateRideOrder = simpleCallRideOrderLogic.onlineOrderSetOffline(id);

        // 新增一键叫车乘客流水 simple_call_customer_flow_log
        SimpleCallCustomerFlowLog customerFlow = new SimpleCallCustomerFlowLog();
        customerFlow.setCustomerId(rideOrder.getCustomerId());
        customerFlow.setAmount(rideOrder.getAmount());
        customerFlow.setInOut(false);
        customerFlow.setCategory(SimpleCallCustomerFlowLogCategory.order_cash);
        customerFlow.setDetail(null);
        customerFlow.setExtra(null);
        customerFlow.setRefId(rideOrder.getId());

        simpleCallCustomerFlowLogMapper.insert(customerFlow);

        // 将 taxi 设置为可用
        boolean updateTaxi = new LambdaUpdateChainWrapper<>(taxiMapper)
                .eq(Taxi::getId, ride.getTaxiId())
                .set(Taxi::getIsAvailable, true)
                .update();

        // 清缓存
        taxiService.clearDriverCache(ride.getTaxiId());

        // 记日志
        operationRecordHelper.addBusinessLog(String.format("将一键叫车行程订单的线上付款方式改为线下现金支付,行程ID [%d]", id));

        return RestResult.success(updateRide && updateRideOrder && updateTaxi);
    }

    @Override
    public RestResult<RideTrackPresenter> getTrack(Long id) {
        SimpleCallRide ride = simpleCallRideMapper.selectById(id);
        if (ObjectUtil.isEmpty(ride)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        RideTrackPresenter res = new RideTrackPresenter();
        res.setId(id);
        res.setCallOrigin(ride.getOrigin());
        res.setCallDestination(ride.getDestination());


        List<com.njtoyo.taxi.admin.mapper.master.entity.SimpleCallRideState> rideStateList = new LambdaQueryChainWrapper<>(simpleCallRideStateMapper)
                .eq(com.njtoyo.taxi.admin.mapper.master.entity.SimpleCallRideState::getRideId, id)
                .list();

        if (ObjectUtil.isNotEmpty(rideStateList)) {
            // 司机接单点
            Optional<com.njtoyo.taxi.admin.mapper.master.entity.SimpleCallRideState> pick_up_contracted = rideStateList.stream()
                    .filter(i -> i.getState().equals(SimpleCallRideState.pickUp))
                    .findFirst();
            pick_up_contracted.ifPresent(rideState -> res.setPickUp(rideState.getLocate()));

            // 实际乘客上车点
            Optional<com.njtoyo.taxi.admin.mapper.master.entity.SimpleCallRideState> origin = rideStateList.stream()
                    .filter(i -> i.getState().equals(SimpleCallRideState.start))
                    .findFirst();
            origin.ifPresent(rideState -> res.setOrigin(rideState.getLocate()));

            // 实际乘客下车点
            Optional<com.njtoyo.taxi.admin.mapper.master.entity.SimpleCallRideState> destination = rideStateList.stream()
                    .filter(i -> i.getState().equals(SimpleCallRideState.end))
                    .findFirst();
            destination.ifPresent(rideState -> res.setDestination(rideState.getLocate()));
        }

        List<SimpleCallRideLocate> rideLocateList = new LambdaQueryChainWrapper<>(simpleCallRideLocateMapper)
                .select(SimpleCallRideLocate::getLocate)
                .eq(SimpleCallRideLocate::getRideId, id)
                .list();

        if (ObjectUtil.isNotEmpty(rideLocateList)) {
            res.setRideLocateLog(rideLocateList.stream().map(SimpleCallRideLocate::getLocate).collect(Collectors.toList()));
        }
        RideRouteMongo rideRouteMongo = rideRouteRepository.getByRideIdAndRideCategory(ride.getId(), "call");
        List<GeoPoint> points = new ArrayList<>();
        if (ObjectUtil.isNotNull(rideRouteMongo)) {
            for (String point : rideRouteMongo.getPoints()) {
                String[] split = StrUtil.split(point, ",");
                GeoPoint geoPoint = new GeoPoint(Convert.toDouble(split[0]), Convert.toDouble(split[1]));
                points.add(geoPoint);
            }
            //预估信息
            res.setEstimatedLocateLog(points);
            res.setEstimatedTime(Convert.toStr(rideRouteMongo.getDuration()));
            res.setEstimatedDistance(Convert.toStr(rideRouteMongo.getDistance()));
        }
        if (ObjectUtil.isNotEmpty(rideLocateList)) {
            res.setRideLocateLog(rideLocateList.stream().map(SimpleCallRideLocate::getLocate).collect(Collectors.toList()));
            //实际信息
            List<GeoPoint> realPoints = new ArrayList<>();
            for (SimpleCallRideLocate rideLocate : rideLocateList) {
                realPoints.add(rideLocate.getLocate());
            }
            double distance = RouteDistanceCalculator.calculateTotalDistance(realPoints);
            res.setRealDistance(Convert.toStr(Math.ceil(distance)));

            Map<com.njtoyo.taxi.admin.mapper.master.enums.SimpleCallRideState, com.njtoyo.taxi.admin.mapper.master.entity.SimpleCallRideState> toMap = rideStateList.stream().collect(Collectors.toMap(com.njtoyo.taxi.admin.mapper.master.entity.SimpleCallRideState::getState, Function.identity()));
            com.njtoyo.taxi.admin.mapper.master.entity.SimpleCallRideState rideStartState = toMap.get(SimpleCallRideState.start);
            com.njtoyo.taxi.admin.mapper.master.entity.SimpleCallRideState rideEndState = toMap.get(SimpleCallRideState.end);
            String realTime = "0";
            if (ObjectUtil.isNotNull(rideStartState) && ObjectUtil.isNotNull(rideEndState)) {
                long between = DateUtil.between(rideStartState.getCreatedAt(), rideEndState.getCreatedAt(), DateUnit.MINUTE);
                realTime = Convert.toStr(between);
                res.setRealTime(realTime);
            }
        }
        return RestResult.success(res);
    }

}
